<?php
defined('IN_IXDCW') or exit('Access Denied');
/**
 * 行情类
 */
class InformationModule extends BasicModule {

	/** @var 模块id */
	private $_moduleid;

	/** @var 条目ID */
	private $_itemid;

	/** @var string 表格 */
	private $_table;

	/** @var string 表格数据 */
	private $_tableData;

	/** @var 是否内容分表 */
	private $_split;

	/** @var array 可用字段 */
	private $_fields;


	/**
	 * constructor
	 * @param $moduleid
	 */
	function __construct($moduleid) {
		parent::__construct();
		global $db, $MOD;
		$this->_moduleid  = $moduleid;
		$this->_table     = $db->getPre().'information';
		$this->_tableData = $db->getPre().'information_data';
		$this->_split     = $MOD['split'];
		$this->_fields = array('aid','catid','carcatid','arbid','arcid','amid','level','title','style','subtitle','introduce','thumb','tag','author','copyfrom','fromurl','voteid','status','hits','username','addtime','editor','edittime','ip','template','islink','linkurl','filepath','note','cartypeid','city');
    }
	public function setItemid($itemid) {
		$this->_itemid = $itemid;
	}

	public function getItemid() {
		return $this->_itemid;
	}

	public function getFields() {
		return $this->_fields;
	}
    public function getTable() {
        return $this->_table;
    }

	/**
	 * 是否通过插入检测
	 * @param $post
	 * @return bool
	 */
	function pass($post) {
		if(!is_array($post)) return false;
		if(!isset($post['upinfo'])){
			if(!$post['catid']) return $this->err(lang('message->pass_catid'));
			if(strlen($post['title']) < 3) return $this->err(lang('message->pass_title'));
			if(isset($post['islink'])) {
				if(!$post['linkurl']) return $this->err(lang('message->pass_linkurl'));
			} else {
				if(!$post['content']) return $this->err(lang('message->pass_content'));
			}
		}
		return true;
	}

	/**
	 * 设置符合内容的值
	 * @param $post
	 * @return array|mixed
	 */
	function set($post) {
		global $MOD, $DT_TIME, $DT_IP, $_username, $r;
		$post['islink'] = isset($post['islink']) ? 1 : 0;
		$post['addtime'] = (isset($post['addtime']) && $post['addtime']) ? strtotime($post['addtime']) : $DT_TIME;
		$post['edittime'] = $DT_TIME;
		$post['title'] = trim($post['title']);
		$post['content'] = stripslashes($post['content']);
		if ($post['content'] && isset($post['clear_link']) && $post['clear_link']) {
			$post['content'] = Post::clearLink($post['content']);
		}
		if ($post['content'] && isset($post['save_remotepic']) && $post['save_remotepic']) {
			$post['content'] = Post::saveRemote($post['content']);
		}
		if ($post['content'] && $post['thumb_no'] && !$post['thumb']) {
			$post['thumb'] = Post::saveThumb($post['content'], $post['thumb_no'], $MOD['thumb_width'], $MOD['thumb_height']);
		}
		if ($post['content'] && !$post['introduce'] && $post['introduce_length']) {
			$post['introduce'] = addslashes(Post::intro($post['content'], $post['introduce_length']));
		}
		if(defined('DT_ADMIN'))	{
			if(!$post['city']){
				$post['city'] = 0;
			}
			$post['city'] = is_array($post['city']) ? $post['city'] : explode(',',$post['city']);
		}
		if(is_array($post['city'])){
			$tmp = '';
			foreach($post['city'] as $v){
				$tmp.= $v.'|';
			}
			$post['city']= '|'.$tmp;
		}
		if ($post['arbid']){
			foreach($post['arbid'] as $v){if(!preg_match("/^\d*$/",$v)){$post['arbid']='';}}
			sort($post['arbid']);
			$post['arbid'] = implode(',',$post['arbid']);
		}else{
			$post['arbid']='';
			$post['arcid']='';
			$post['amid']='';
		}
		if ($post['arcid'] && $post['arbid']){
			foreach($post['arcid'] as $v){if(!preg_match("/^\d*$/",$v)){$post['arcid']='';}}
			sort($post['arcid']);
			$post['arcid'] = implode(',',$post['arcid']);
		}else{
			$post['arcid']='';
			$post['amid']='';
		}
		if ($post['arcid'] && $post['arbid'] && $post['amid']){
			foreach($post['amid'] as $v){if(!preg_match("/^\d*$/",$v)){$post['amid']='';}}
			sort($post['amid']);
			$post['amid'] = implode(',',$post['amid']);
		}else{
			$post['amid']='';
		}
		if($this->_itemid) {
			// 处理新传入的img
			$r   = $this->getOne();
			$post['editor'] = $_username;
		} else {
			$post['ip']       = $DT_IP;

		}
		if(!defined('DT_ADMIN')) {
			$content = $post['content'];
			unset($post['content']);
			$post = Str::htmlSpecialChars($post);
			$post['content'] = Str::safe($content);
		}
		$post['content'] = addslashes($post['content']);
		return $post;
	}

	/**
	 * 获取一条数据
	 * @return array|void
	 */
	function getOne() {
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
        return $this->_db->getOne("SELECT * FROM {$this->_table} a,{$content_table} c WHERE a.itemid=c.itemid and a.itemid=$this->_itemid");
	}

	/**
	 * 获取列表
	 * @param string $condition
	 * @param string $order
	 * @param string $cache
	 * @return array
	 */
	function getList($condition = 'status=3', $order = 'addtime DESC', $cache = '') {
		global $MOD,$items;
		$num = $this->_db->count($this->_table, $condition, $cache);
		$items=$num;
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "SELECT * FROM {$this->_table}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$lists = $catids = $CATS = array();
		$result = $this->_db->query($sql, $cache);
		while($r = $this->_db->fetchArray($result)) {
			$r['adddate'] = timetodate($r['addtime'], 5);
			$r['editdate'] = timetodate($r['edittime'], 5);
			$r['alt'] = $r['title'];
			$r['title'] = set_style($r['title'], $r['style']);
			$catids[$r['catid']] = $r['catid'];
			$lists[] = $r;
		}
		if($catids) {
			$result = $this->_db->query("SELECT catid,catname,linkurl FROM {$this->_db->pre}category WHERE catid IN (".implode(',', $catids).")");
			while($r = $this->_db->fetchArray($result)) {
				$CATS[$r['catid']] = $r;
			}
			if($CATS) {
				foreach($lists as $k=>$v) {
					$lists[$k]['catname'] = $v['catid'] ? $CATS[$v['catid']]['catname'] : '';
					$lists[$k]['caturl'] = $v['catid'] ? $MOD['linkurl'].'?catid='.$v['catid'] : '';
				}
			}
		}
		return $lists;
	}

	/**
	 * 添加数据
	 * @param $post
	 */
	function add($post) {
		global $MOD,$_userid,$L,$_username,$_money;
		$post = $this->set($post);
		$this->_db->query(Sql::insert($this->_table, $post, $this->_fields));
		$this->_itemid = $this->_db->insertId();
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
		$this->_db->query("INSERT INTO {$content_table} (itemid,content) VALUES ('$this->_itemid', '$post[content]')");
		$this->update($this->_itemid, $post, $post['content']);
		if(!defined('DT_ADMIN')){
			if(isset($post['total']) && $post['total'] > 0 && $post['total'] < $_money){
				money_add($_username, -$post['total']);
				money_record($_username, -$post['total'], $L['in_site'], 'system', '发布'.$MOD['name'].'扣款','ID:'.$this->_itemid);
			}
		}
		ThumbUpload::clearPicture($this->_moduleid.'_thumb', $post['thumb'], '', $_userid);
		EditorUpload::clearDiff($post['content'], '', $_userid);
		return $this->_itemid;
	}

	/**
	 * 编辑
	 * @param $post
	 * @return bool
	 */
	function edit($post) {
		global $_userid,$r;
		$this->delete($this->_itemid, false);
		$post = $this->set($post);
		$this->_db->query(Sql::update($this->_table, $post, "itemid={$this->_itemid}", '', $this->_fields));
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
	    $this->_db->query(Sql::update($content_table,"content='$post[content]'","itemid=$this->_itemid"));
		$this->update($this->_itemid, $post, $post['content']);
		ThumbUpload::clearPicture($this->_moduleid.'_thumb', $post['thumb'], $r['thumb'], $_userid);
		EditorUpload::clearDiff($post['content'], $r['content'], $_userid);
		return true;
	}



	/**
	 * 更新
	 * @param        $itemid
	 * @param array  $item
	 * @param string $content
	 */
	function update($itemid, $item = array(), $content = '') {
		$item or $item = $this->_db->getOne("SELECT * FROM {$this->_table} WHERE itemid=$itemid");
		$keyword = $item['title'].','.str_replace(' ', ',', $item['tag']).','.strip_tags(cat_pos($item['catid'], ','));
		$keyword = str_replace("//", '', addslashes($keyword));
		$item['itemid'] = $itemid;
		$sql = "keyword='$keyword'";
		$this->_db->query(Sql::update($this->_table,"$sql","itemid=$itemid"));
	}

	/**
	 * 回收站
	 * @param $itemid
	 * @return bool
	 */
	function recycle($itemid) {
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->recycle($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"status=0","itemid=$itemid"));
			$this->delete($itemid, false);
			return true;
		}		
	}

	/**
	 * 还原
	 * @param $itemid
	 * @return bool
	 */
	function restore($itemid) {
		global $module, $MOD;
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->restore($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"status=3","itemid=$itemid"));
			return true;
		}		
	}

	/**
	 * 删除条目
	 * @param      $itemid
	 * @param bool $all
	 */
	function delete($itemid, $all = true) {
		if(is_array($itemid)) {
			foreach($itemid as $v) { 
				$this->delete($v, $all);
			}
		} else {
			$this->_itemid = $itemid;
			$r = $this->getOne();
			if($all) {
				$userid = get_user($r['username']);
				if ($r['thumb']) PictureUpload::deletePicture($r['thumb'], $userid);
				if ($r['content']) EditorUpload::clearDiff('', $r['content'], $userid);
				$this->_db->query(Sql::delete($this->_table,"itemid=$itemid"));
				$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
				$this->_db->query(Sql::delete($content_table,"itemid=$itemid"));
			}
		}
	}

	/**
	 * 检测
	 * @param $itemid
	 * @return bool
	 */
	function check($itemid) {
		global $_username, $DT_TIME;
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->check($v); }
		} else {
			$this->_itemid = $itemid;
			$this->_db->query(Sql::update($this->_table,"status=3,hits=hits+1,editor='$_username',edittime=$DT_TIME","itemid=$itemid"));
			return true;
		}
	}

	/**
	 * 未通过审核
	 * @param $itemid
	 * @return bool
	 */
	function reject($itemid) {
		global $_username, $DT_TIME;
		if(is_array($itemid)) {
			foreach($itemid as $v) { $this->reject($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"status=1,editor='$_username'","itemid=$itemid"));
			return true;
		}
	}

	/**
	 * 清空回收站内容
	 * @param string $condition
	 */
	function clear($condition = 'status=0') {		
		$result = $this->_db->query("SELECT itemid FROM {$this->_table} WHERE $condition ");
		while($r = $this->_db->fetchArray($result)) {
			$this->delete($r['itemid']);
		}
	}

	/**
	 * 级别设置
	 * @param $itemid
	 * @param $level
	 */
	function level($itemid, $level) {
		$itemids = is_array($itemid) ? implode(',', $itemid) : $itemid;
		$this->_db->query(Sql::update($this->_table,"level=$level","itemid IN ($itemids)"));
	}

}
